"""
--------------------------------------
FileName: work.1.py
Content: 
        验证ch3.work2算法的正确性

Date:    25/09/15
Auther:  杨则瑞
Encode:  utf-8 | CRLF
--------------------------------------
"""



import csv
import subprocess
import io
import os
import sys
import random

from math import sqrt
from math import floor

failCnt = 0



def generate_test_case():

    num  = random.randint(0, 100)
    num_m = random.randint(0, 100000)


    # Fmting
    inpt = bytes()
    inpt += (bytes(str(num) + '\n',encoding="ascii"))
    inpt += (bytes(str(num_m) + '\n',encoding="ascii"))

    ttcnt = dict()

    for i in range(0,num):
        key = random.randint(-100,100)

        inpt += (bytes(str(key) + '\n',encoding="ascii"))
        if key not in ttcnt:
            ttcnt[key] = 0

    for i in range(0,num_m):
        q = random.randint(-100,100)
        inpt += (bytes(str(q) + '\n',encoding="ascii"))

        if q in ttcnt:
            ttcnt[q] += 1


            

    return inpt, ttcnt







abr = 15
def get_shorter(s : str):
    if len(s) < abr + 3:
        return s
    return "{}...{}".format(s[:abr],s[-abr:])

for case in range(0,10):

    sys.stdout.write("Testing case %d " % case)
    
    target = (sys.argv[1])

    handler = subprocess.Popen(target,
                           stdin  = subprocess.PIPE,
                           stdout = subprocess.PIPE,
                           stderr = subprocess.STDOUT)

    
    if not handler.stdin.writable:

        print("Communication Error.")
        exit(1)
    if not handler.stdout.readable:
        print("Communication Error.")
        exit(2)

    flag : bool = True
    



    inpt , oue = generate_test_case() 


     # 获取输出
    out, _ = handler.communicate(inpt)
    out = out.decode("ascii")

    ttcnt = dict()
    outlist = list(map(int,out.split()))
    

    prev = 0

    l = len(outlist)
    if l > 2:
        prev = outlist[1]

    for i in range(0,l,2):
        
        # 不增
        if outlist[i + 1] > prev:
            flag = False
            break

        prev = outlist[i + 1]

        # 计数正确
        if outlist[i] in ttcnt:
            ttcnt[outlist[i]] += outlist[i + 1]
        else:
            ttcnt[outlist[i]] = outlist[i + 1]

    ttcnt = dict(sorted(ttcnt.items()))
    oue = dict(sorted(oue.items()))

    sys.stdout.write("\nJudging if {} equals to {} ".format(get_shorter(str(ttcnt)), get_shorter(str(oue))))
    # 判断相等
    flag = flag and (ttcnt == oue)
    

    if(flag == True):
        print("\033[1;32m""Pass""\033[0;10m")
    else:
        failCnt += 1
        print("\033[1;31m""Fail""\033[0;10m") 
                
    
print("Result:")

if failCnt == 0:
    print("\033[1;32m""All Pass.""\033[0;10m")
else :
    print("\033[1;10m""{} Fails cases".format(failCnt))